package com.mrobuy.jdvc.dao.impl;

import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.entity.VCCategory;
import com.mrobuy.util.Pagination;
import com.mrobuy.jdvc.dao.VCBrandDao;
import com.mrobuy.jdvc.entity.VCBrand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;

@Repository("vcBrandDao")
public class VCBrandDaoImpl extends CommonDaoImpl implements VCBrandDao {

    private static Logger LOG = LoggerFactory.getLogger(VCBrandDao.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<VCBrand> list() {

        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT * from VC_BRAND");
        try {
            List<VCBrand> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(VCBrand.class));
            return list;
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        return Collections.EMPTY_LIST;
    }

    @Override
    public Pagination load(int start, int length) {
        Pagination pagination = new Pagination();

        try {
            int count = jdbcTemplate.queryForObject("select count(*) from VC_BRAND", Integer.class);
            List<VCBrand> list = jdbcTemplate.query("select * from VC_BRAND limit ?, ?", new Object[] { start, length }, new BeanPropertyRowMapper(VCBrand.class));


            pagination.setRecordsTotal(count);
            pagination.setRecordsFiltered(count);
            pagination.setData(list);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        return pagination;
    }

    @Override
    public VCBrand load(String brandid) {
        if (StringUtils.isBlank(brandid)) {
            return null;
        }

        try {
            return (VCBrand)jdbcTemplate.queryForObject("select * from VC_BRAND where BRANDID = ?", new Object[]{brandid}, new BeanPropertyRowMapper(VCBrand.class));
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

        return null;
    }

    @Override
    public VCBrand load(String brandid, String vendor) {
        if (StringUtils.isBlank(brandid)) {
            return null;
        }

        try {
            return (VCBrand)jdbcTemplate.queryForObject("select * from VC_BRAND where BRANDID = ? and VENDOR = ? ", new Object[]{brandid, vendor}, new BeanPropertyRowMapper(VCBrand.class));
        } catch (Exception e) {
        }

        return null;
    }
}
